package com.cn.qgx428.lazydiary.Presenter

import android.text.TextUtils
import android.util.Log
import com.cn.qgx428.lazydiary.Presenter.contract.PlanContract
import com.cn.qgx428.lazydiary.Utils.ToastHelper
import com.cn.qgx428.lazydiary.network.Code
import com.cn.qgx428.lazydiary.network.Imageloader
import com.cn.qgx428.lazydiary.network.NetworkManager
import com.cn.qgx428.lazydiary.network.bean.*
import com.j256.ormlite.stmt.query.In
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*

/**
 * Created by qinguanxiong on 2018/3/11.
 */
class PlanPresenter {
    companion object {
        fun createPlan(userId: Int, planName:String, createTime:String, endTime:String,
                       planImage:String = "plan_default", imagePath: String,status:String = "进行中", listener: (planId: Int)->Unit){
            // 使用默认图片
            if (TextUtils.isEmpty(imagePath)){
                NetworkManager.getInstance()
                        .getPlanService()
                        .updateUserInfo(userId, planName, planImage, createTime, endTime, status)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({
                            listener(it.code.toInt())
                        })
            }
            // 自定义图片
            else{
                Imageloader.upload(imagePath, planImage,{
                    NetworkManager.getInstance()
                            .getPlanService()
                            .updateUserInfo(userId, planName, planImage, createTime, endTime, status)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe({
                                // 此处code是从后台返回的plan id
                                listener(it.code.toInt())
                            })
                })
            }
        }

        /**
         * 获取计划表
         */
        fun getPlans(userId: Int, listener: (res: PlansResponse) -> Unit){
            NetworkManager.getInstance()
                    .getPlanService()
                    .getPlans(userId)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        // 此处code是从后台返回的plan id
                        listener(it)
                    })
        }

        fun deletePlan(id: Int, listener: () -> Unit){
            NetworkManager.getInstance()
                    .getPlanService()
                    .deletePlan(id)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<CommonResponse>{
                        override fun onError(e: Throwable?) {
                            ToastHelper.toast("服务器错误")
                            Log.d("what the hell", e?.message)
                        }

                        override fun onNext(t: CommonResponse?) {
                            ToastHelper.toast(t!!.msg)
                            listener()
                        }

                        override fun onCompleted() {
                        }
                    })
        }

        /**
         * 获取计划详情
         */
        fun getPlanDetail(planId: Int, listener: PlanContract.IPlanDetail){
            NetworkManager.getInstance()
                    .getPlanService()
                    .getPlanDetail(planId)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<PlanDetailResponse>{
                        override fun onError(e: Throwable?) {
                            ToastHelper.toast("服务器错误")
                            Log.d("what the hell", e?.message)
                        }

                        override fun onNext(t: PlanDetailResponse?) {
                            if (t?.code == Code.SUCCESS_WITH_NOTDATA){
                                listener.onNoPlanDetailData()
                            } else {
                                listener.onGetPlanDetalData(t!!.planDetails)
                            }
                        }

                        override fun onCompleted() {
                        }
                    })
        }

        /**
         * 更新计划详情
         */
        fun updatePlanDetail(details: List<PlanDetail>, listener: ()->Unit){
            var total = 0
            val lock = Any()
            details.forEach {
                NetworkManager.getInstance()
                        .getPlanService()
                        .updatePlanDetail(it.planid, it.id, it.content, it.createtime)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({
                            synchronized(lock,{
                                total++
                                if (total == details.size)
                                    listener()
                            })
                        })
            }
        }

        /**
         * 删除
         */
        fun removePlanDetail(id: Int, listener: (msg:String) -> Unit){
            NetworkManager.getInstance()
                    .getPlanService()
                    .removePlanDetail(id)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<CommonResponse>{
                        override fun onError(e: Throwable?) {
                            ToastHelper.toast("服务器出错")
                        }

                        override fun onNext(t: CommonResponse?) {
                            listener(t!!.msg)
                        }


                        override fun onCompleted() {

                        }
                    })
        }

        /**
         * 检查打卡状态
         */
        fun checkClockIn(planId: Int, time:String, listener: (code: String) -> Unit){
            NetworkManager.getInstance()
                    .getPlanService()
                    .checkClockIn(planId, time)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<CommonResponse>{
                        override fun onError(e: Throwable?) {
                            //ToastHelper.toast("服务器出错")
                            // json 不能转化空对象， 此处在逻辑上不为错， 拦截此次错误， 通知页面无数据
                            listener("-1")
                        }

                        override fun onNext(t: CommonResponse?) {
                            listener(t!!.code)
                        }

                        override fun onCompleted() {

                        }
                    })
        }

        /**
         * 打卡
         */
        fun clockIn(planId: Int, content: List<String>, remark: String, time: String, listener: () -> Unit){
            // 组织数据
            val builder: StringBuilder = StringBuilder()
            content.forEach {
                builder.append(it)
                builder.append(",")
            }
            NetworkManager.getInstance()
                    .getPlanService()
                    .clockIn(planId, builder.toString(), remark, time)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<CommonResponse>{
                        override fun onError(e: Throwable?) {
                            ToastHelper.toast("服务器出错")
                            Log.d("what the hell", e!!.message)
                        }

                        override fun onNext(t: CommonResponse?) {
                            listener()
                        }

                        override fun onCompleted() {
                        }
                    })

        }

        /**
         * 历史打卡
         */
        fun getHistoryClockIn(planId: Int, listener: (history: List<PlanClockIn>) -> Unit){
            NetworkManager.getInstance()
                    .getPlanService()
                    .historyClockIn(planId)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<PlanHistoryClockInResponse>{
                        override fun onError(e: Throwable?) {
                            listener(arrayListOf<PlanClockIn>())
                            Log.d("what the hell", e?.message)
                        }

                        override fun onNext(t: PlanHistoryClockInResponse?) {
                            listener(t!!.history)
                        }

                        override fun onCompleted() {

                        }
                    })
        }
    }
}